<template>
    <div class="white-box">
        <div class="mco-item">
            <title-more title="会员信息" />
            <div class="od-one">
                <div class="od-one__item">
                    <detail-item title="微信昵称" one-value bottom="16px" :value="objs.nickname || '--'" />
                    <detail-item title="会员等级" one-value bottom="16px" :value="objs.grade_id > 0 ? objs.grade.level_name : '--'" />
                    <detail-item title="累计消费" one-value bottom="16px" :value="objs.total_pay || '0.00'" />
                </div>
                <div class="od-one__item">
                    <detail-item title="会员UID" one-value bottom="16px" :value="objs.uid" />
                    <detail-item title="手机号码" one-value bottom="16px" :value="objs.mobile || '--'" />
                    <detail-item title="订单数" one-value bottom="16px" :value="objs.orders || '0'" />
                </div>
                <div class="od-one__item">
                    <detail-item title="会员姓名" one-value bottom="16px" :value="objs.name || '--'" />
                    <detail-item title="当前余额" one-value bottom="16px" :value="objs.money || '0.00'" />
                    <detail-item title="授信余额" one-value bottom="16px" :value="objs.credit || '0.00'" />
                </div>
            </div>
            <detail-item title="默认收货地址" one-value bottom="16px" :value="objs.user_addr.addr + objs.user_addr.house" v-if="objs.user_addr" />
        </div>

        <div class="mco-item">
            <title-more title="选择商品" />
            <!-- <el-button type="primary" @click="dialogGoods = true">添加商品</el-button> -->
            <!-- max-height="800px" -->
            <el-table
                class="table-mb"
                :data="select_goods"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                style="margin-top: 0"
            >
                <el-table-column prop="index" width="74">
                    <template #default="scope">
                        <div class="table-oper flexs">
                            <el-icon size="20px" color="#646566" @click="addRecord"><Plus /></el-icon>
                            <el-icon size="20px" color="#646566" @click="delGood(scope.row, scope.$index)"><Minus /></el-icon>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="商品信息" min-width="220">
                    <template #default="scope">
                        <div class="table-lr" v-if="scope.row.product_img && scope.row.product_name">
                            <el-image
                                class="table-lr__img"
                                :src="proxy.imgUrl + scope.row.product_img + '!img_400'"
                                fit="cover"
                                style="width: 22px; height: 22px"
                                v-if="scope.row.product_img"
                            />
                            <div class="table-lr__right" style="min-height: 22px">
                                <p class="lr-title line-one" style="margin-bottom: 0">{{ scope.row.product_name }}</p>
                            </div>
                        </div>
                        <!-- 筛选和选择商品 -->
                        <div class="select-good" v-else>
                            <el-popover placement="bottom-start" :width="800" :visible="popCur === scope.$index">
                                <template #reference>
                                    <el-input
                                        v-model.trim="good_name"
                                        clearable
                                        placeholder="输入商品名称"
                                        @input="bindInput"
                                        @blur="popCur = null"
                                        @click="clickPopover(scope.$index)"
                                    />
                                </template>
                                <div class="good-list">
                                    <template v-if="goods.length > 0">
                                        <div
                                            :class="[{ disabled: item.disabled }, 'good-item']"
                                            v-for="(item, index) in goods"
                                            :key="index"
                                            @click.stop="item.disabled ? '' : selectGoods(item, index)"
                                        >
                                            <span class="good-pid">{{ item.product_id }}</span>
                                            <el-image
                                                class="good-img"
                                                :src="proxy.imgUrl + item.product_img + '!img_400'"
                                                fit="cover"
                                                v-if="item.product_img"
                                            />
                                            <p class="good-title line-one">{{ item.product_name }}</p>
                                            <span class="good-attr line-one">供应商:{{ item.supplier_title }}</span>
                                            <span class="good-attr">{{ item.norm }}/{{ item.unit }}</span>
                                            <span class="good-color">{{ item.color }}，{{ item.level }}</span>
                                        </div>
                                    </template>
                                    <p class="good-none" v-else>未能搜索到相关商品！</p>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="供应商" min-width="150">
                    <template #default="{ row }">
                        <span v-if="row.supplier_title">{{ row.supplier_title }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="规格" min-width="120">
                    <template #default="{ row }">
                        <span v-if="row.norm">{{ row.norm }}/{{ row.unit }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="level" label="等级" min-width="120"></el-table-column>
                <el-table-column prop="sku" label="库存" min-width="120"></el-table-column>
                <el-table-column label="数量" min-width="190">
                    <template #default="{ row }">
                        <el-input-number v-model="row.nums" :min="1" :max="row.sku" @change="changeStepper" @blur="blurInput(row)" v-if="row.product_id != 0" />
                    </template>
                </el-table-column>
                <el-table-column label="价格" min-width="160">
                    <template #default="{ row }">
                        <el-input
                            v-model.trim="row.product_price"
                            clearable
                            oninput="value=value.replace(/[^\d.]/g,'')"
                            style="width: 130px"
                            placeholder="请输入价格"
                            min="0"
                            @change="changeThreePrice"
                            v-if="row.product_name"
                        />
                    </template>
                </el-table-column>
            </el-table>
            <div class="good-foot">
                <detail-item title="原价" one-value bottom="16px" title-width="80px" :value="originalPrice" />
                <detail-item class="exp-detail" bottom="16px" title-width="auto" title="优惠价" style="margin-left: 24px">
                    <el-input
                        ref="priceRef"
                        v-model.trim="prices"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入花材费"
                        @change="priceBlur"
                        style="width: 140px"
                    />
                </detail-item>
                <detail-item class="exp-detail" bottom="16px" title-width="auto" title="打包费" style="margin-left: 24px">
                    <el-input
                        ref="priceRef"
                        v-model.trim="pack_amount"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入打包费"
                        @change="changeFootPrice"
                        style="width: 140px"
                    />
                </detail-item>
                <detail-item class="exp-detail" bottom="16px" title-width="auto" title="物流运费" style="margin-left: 24px">
                    <el-input
                        ref="priceRef"
                        v-model.trim="freight"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入物流运费"
                        @blur="changeFootPrice"
                        style="width: 140px"
                    />
                </detail-item>
                <detail-item
                    title="整单优惠"
                    one-value
                    bottom="16px"
                    title-width="80px"
                    :value="originalPrice - prices <= 0 ? '0.00' : originalPrice - prices"
                />
                <detail-item title="合计金额" one-value bottom="16px" title-width="80px" :value="totalPrice" />
            </div>
        </div>

        <div class="mco-item">
            <title-more title="详情信息" />
            <detail-item class="exp-detail" title="配送方式" bottom="16px">
                <el-select v-model="pei_type" clearable placeholder="请选择配送方式" style="width: 260px" @change="changePeiType">
                    <el-option label="快递物流" value="1" />
                    <el-option label="到店自提" value="0" />
                </el-select>
            </detail-item>
            <detail-item title="支付方式" bottom="16px">
                <el-radio-group v-model="pay_code">
                    <el-radio label="money">余额支付</el-radio>
                    <el-radio label="credit">授信额支付</el-radio>
                </el-radio-group>
            </detail-item>
            <template v-if="pei_type == 0">
                <detail-item class="exp-detail" bottom="16px" title="自提联系人">
                    <el-input v-model.trim="self_contact" clearable style="width: 260px" placeholder="请输入自提联系人" />
                </detail-item>
                <detail-item class="exp-detail" bottom="16px" title="自提联系电话">
                    <el-input
                        v-model.trim="self_mobile"
                        clearable
                        maxlength="11"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        style="width: 260px"
                        placeholder="请输入自提联系电话"
                    />
                </detail-item>
                <detail-item class="exp-detail" bottom="16px" title="站点自提">
                    <el-select v-model="dc_id" filterable clearable placeholder="请选择自提点(输入关键词可搜索)" style="width: 260px">
                        <el-option v-for="item in sites" :key="item.dc_id" :label="item.title" :value="item.dc_id" />
                    </el-select>
                </detail-item>
            </template>
            <template v-if="pei_type == 1">
                <detail-item class="exp-detail" title="物流公司" bottom="16px">
                    <el-select
                        v-model="company_id"
                        clearable
                        filterable
                        placeholder="选择物流公司(输入关键词可搜索)"
                        style="width: 260px"
                        @change="changeCompany"
                    >
                        <el-option :label="item.title" :value="item.company_id" v-for="(item, index) in companys" :key="index" />
                    </el-select>
                </detail-item>
                <detail-item class="exp-detail" bottom="16px" title="收货地址">
                    <el-select v-model="addr_id" filterable clearable placeholder="请选择收货地址(输入关键词可搜索)">
                        <el-option v-for="item in addrArrs" :key="item.addr_id" :label="item.addr + item.house" :value="item.addr_id" />
                    </el-select>
                    <el-button type="primary" @click.stop="dialogAddr = true">添加新地址</el-button>
                </detail-item>
            </template>
            <detail-item class="exp-detail" bottom="16px" title="订单归属日期">
                <el-date-picker v-model="delivery_day" type="date" value-format="YYYY-MM-DD" style="width: 260px" placeholder="请选择订单归属日期" />
            </detail-item>
            <detail-item class="exp-detail" bottom="16px" title="订单备注">
                <el-input v-model.trim="order_remarks" type="textarea" clearable :rows="3" style="width: 400px" placeholder="请输入订单备注(选填)" />
            </detail-item>
        </div>

        <!-- 固定底部按钮 -->
        <div class="foot-btn flexs-center" style="margin-top: 30px">
            <el-button type="primary" plain @click="clickPreview">订单预览</el-button>
            <el-button type="primary" :loading="form_loading" @click="clickOrders">创建订单</el-button>
        </div>

        <!-- 添加地址 -->
        <el-dialog v-model="dialogAddr" title="添加地址" width="580px" :append-to-body="true" :destroy-on-close="true" @close="closeAddr">
            <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
                <el-form-item label="收货人姓名" prop="name">
                    <el-input v-model.trim="ruleForm.name" clearable placeholder="请输入收货人姓名" />
                </el-form-item>
                <el-form-item label="手机号" prop="tel">
                    <el-input v-model.trim="ruleForm.tel" oninput="value=value.replace(/[^\d]/g,'')" maxlength="11" clearable placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="经纬度" prop="lat_lng">
                    <el-input
                        v-model.trim="ruleForm.lat_lng"
                        readonly
                        :suffix-icon="ArrowRight"
                        placeholder="请选择当前位置的经纬度"
                        clearable
                        @click="clickLatAndLng"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="所在地区" prop="area_code">
                    <el-cascader ref="cascaderRef" v-model="ruleForm.area_code" :props="props" :options="allArea" clearable placeholder="请选择省市区" />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model.trim="ruleForm.address" type="textarea" clearable :rows="3" placeholder="请输入详细地址" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)">确认</el-button>
                        <el-button @click="resetForm(ruleRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 获取经纬度 -->
        <el-dialog v-model="dialogMap" title="获取经纬度" width="600px" :close-on-click-modal="false" :append-to-body="true" :destroy-on-close="true" draggable>
            <div class="p16">
                <div class="task-one">
                    <div class="task-one__item">
                        <span class="task-one__label">地址：</span>
                        <el-input placeholder="输入地址获取经纬度" v-model.trim="addrs" clearable style="width: 280px"></el-input>
                    </div>
                    <div class="task-one__btn">
                        <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">获取</el-button>
                    </div>
                </div>
                <div id="container"></div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="confirmMap">确认地址</el-button>
                    <el-button @click="dialogMap = false">取消</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 订单预览 -->
        <el-drawer
            title="订单预览"
            class="mco-drawer"
            v-model="drawerOrder"
            direction="rtl"
            size="1300px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="drawerOrder = false"
        >
            <div class="xq-box">
                <div class="prev-box flexs">
                    <div class="prev-item">
                        <detail-item title="订单日期" one-value title-width="60px" bottom="6px" :value="delivery_day || ''" />
                        <detail-item title="客户姓名" one-value title-width="60px" bottom="6px" :value="pei_type == 1 ? objs.name : self_contact" />
                        <detail-item
                            title="收货地址"
                            one-value
                            title-width="60px"
                            bottom="6px"
                            :value="objs.user_addr ? objs.user_addr.addr + objs.user_addr.house : ''"
                        />
                    </div>
                    <div class="prev-item">
                        <detail-item
                            title="配送方式"
                            one-value
                            title-width="60px"
                            bottom="6px"
                            :value="`快递物流${company_name ? '-' + company_name : ''}`"
                            v-if="pei_type == 1"
                        />
                        <detail-item title="配送方式" one-value title-width="60px" bottom="6px" value="到店自提" v-if="pei_type == 0" />
                        <detail-item title="联系电话" one-value title-width="60px" bottom="6px" :value="pei_type == 1 ? objs.mobile : self_mobile" />
                        <detail-item title="订单备注" one-value title-width="60px" bottom="6px" :value="order_remarks" />
                    </div>
                </div>

                <!-- 选中的商品 -->
                <div class="prev-table">
                    <div class="table-head">
                        <div class="table-body__left flexs">
                            <div class="table-head__one">序号</div>
                            <div class="table-head__two">货品名称</div>
                            <div class="table-head__six">规格</div>
                            <div class="table-head__five">等级</div>
                            <div class="table-head__three">数量</div>
                            <div class="table-head__four">金额</div>
                            <div class="table-head__null"></div>
                        </div>
                        <div class="table-body__left flexs">
                            <div class="table-head__one">序号</div>
                            <div class="table-head__two">货品名称</div>
                            <div class="table-head__six">规格</div>
                            <div class="table-head__five">等级</div>
                            <div class="table-head__three">数量</div>
                            <div class="table-head__four">金额</div>
                        </div>
                    </div>
                    <div class="table-cont" v-if="select_goods.length > 1">
                        <!-- 选择商品 -->
                        <div class="table-body">
                            <div class="table-body__left flexs" v-for="(item, index) in prevArrs" :key="index">
                                <div class="table-head__one">
                                    <span v-if="item.product_name">{{ index + 1 }}</span>
                                </div>
                                <div class="table-head__two">{{ item.product_name }}</div>
                                <div class="table-head__six">
                                    <span v-if="item.norm">{{ item.norm }}/{{ item.unit }}</span>
                                </div>
                                <div class="table-head__five">{{ item.level }}</div>
                                <div class="table-head__three">{{ item.nums }}</div>
                                <div class="table-head__four">{{ item.product_price }}</div>
                                <div class="table-head__null" :style="{ display: index % 2 > 0 ? 'none' : 'block' }"></div>
                            </div>
                        </div>
                        <!-- 底部 -->
                        <div class="table-foot">
                            <div class="table-foot__line flexs">
                                <p class="table-foot__title">
                                    原价：<span class="table-foot__value">{{ originalPrice }}</span>
                                </p>
                                <p class="table-foot__title">
                                    优惠价：<span class="table-foot__value">{{ prices }}</span>
                                </p>
                                <p class="table-foot__title">
                                    打包费：<span class="table-foot__value">{{ pack_amount }}</span>
                                </p>
                                <p class="table-foot__title">
                                    物流费用：<span class="table-foot__value">{{ freight }}</span>
                                </p>
                                <p class="table-foot__title">
                                    整单优惠：<span class="table-foot__value">{{ originalPrice - prices <= 0 ? "0.00" : originalPrice - prices }}</span>
                                </p>
                                <p class="table-foot__title">
                                    合计金额：<span class="table-foot__value">{{ totalPrice }}</span>
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="table-none" v-else>暂无数据</div>
                </div>
            </div>
        </el-drawer>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, onBeforeUnmount } from "vue"
import { useRouter, useRoute } from "vue-router"
import { Search, ArrowRight, Plus, Minus } from "@element-plus/icons-vue"
import { jsonp } from "vue-jsonp"
import GoBack from "@components/GoBack.vue"
import TitleMore from "@components/title-more.vue"
import DetailItem from "@components/DetailItem.vue"

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

let uid = route.query.uid
onMounted(() => {
    uid && getDetail()
    getArea()
    addRecord()
})

onBeforeUnmount(() => {
    map = null
    marker = null
    cascaderRef.value = null
    ruleRef.value = null

    // 移除绑定事件
    window.removeEvent = function () {
        qq.maps.event.removeListener(eventDragend)
        eventDragend = null
    }
})

const objs = ref({})
function getDetail() {
    proxy.$axios
        .get("user/order/userInfo", {
            params: {
                uid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                addr_id.value = result.user_addr ? result.user_addr.addr_id : ""
                objs.value = result
                getGoods()
                getCompany()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 选择商品
 * @param {String} originalPrice 原价
 * @param {String} prices 现价
 * @param {String} good_name 搜索字段
 * @param {Array} select_goods 已选择的商品数组
 * @param {Number} popCur 商品弹窗下标
 * @param {Function} selectGoods 选择商品
 */
const originalPrice = ref(0)
const prices = ref(0)
const select_goods = ref([])
const good_name = ref("")
const addRecord = () => {
    select_goods.value.push({ product_id: 0 })
}
// 文本框搜索商品，使用到函数防抖，默认
const bindInput = proxy.$util.debounce(() => {
    getGoods()
}, 300)
const popCur = ref(null)
const clickPopover = (index) => {
    popCur.value = index
}
const selectGoods = (item, index) => {
    item.nums = 1
    item.disabled = true
    select_goods.value.unshift(item)
    goods.value[index].disabled = true
    popCur.value = null
    good_name.value = ""
    calculation()
}
// 调整花材费
const priceRef = ref(null)
const priceBlur = () => {
    if (prices.value - originalPrice.value > 0) {
        proxy.$message({ message: "请输入低于原价的金额！", type: "warning" })
        priceRef.value.focus() // 设置文本框聚焦
        priceRef.value.select() // 设置文本框选中
        popCur.value = null
        return
    }
    let total_all = Number(prices.value) + Number(pack_amount.value) + Number(freight.value)
    totalPrice.value = total_all.toFixed(2)
}
// 修改商品数量
const changeStepper = (val, oldval) => {
    calculation()
}
// 当失去焦点且数量为0时
const blurInput = (row) => {
    row.nums == null && (row.nums = 1)
}
// 修改打包/运费
const changeFootPrice = (val) => {
    let all_price = 0
    if (prices.value) {
        all_price = Number(prices.value) + Number(pack_amount.value) + Number(freight.value)
        totalPrice.value = all_price.toFixed(2)
        return
    }
    calculation()
}

// 修改商品单价
const changeThreePrice = (val) => {
    calculation()
}
// 计算价格
const totalPrice = ref(0)
function calculation() {
    let total = 0
    select_goods.value.map((item) => {
        if (item.product_id > 0) {
            total += parseInt(item.product_price * 100 * (item.nums * 100)) / 10000
        }
    })
    prices.value = originalPrice.value = total

    let total_all = total + Number(pack_amount.value) + Number(freight.value)
    totalPrice.value = total_all.toFixed(2)
}

/**
 * 选择商品和删除操作
 * @param {Number} good_page 页码
 * @param {Number} good_total 总数
 * @param {Array} goods 商品数组
 * @param {Array} leave_list 等级数组
 */
const good_page = ref(1)
const good_total = ref(0)
const goods = ref([])
const delGood = (row, index) => {
    let indexs = goods.value.findIndex((item) => item.product_id === row.product_id)
    if (indexs > -1) {
        goods.value[indexs].disabled = false
    }
    select_goods.value.splice(index, 1)
}
function getGoods() {
    proxy.$axios
        .get("user/order/product", {
            params: {
                page: good_page.value,
                limit: 30,
                so: good_name.value,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                result.map((item) => {
                    let index = select_goods.value.findIndex((sub) => item.product_id === sub.product_id)
                    item.disabled = index > -1 ? true : false
                })
                good_total.value = res.data.count
                goods.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 切换配送方式，0是自提，1是物流
const pei_type = ref("1")
const changePeiType = (val) => {
    pei_type.value = val
    val == 0 ? getSites() : getCompany()
}
// 物流公司
const company_id = ref("")
const company_name = ref("")
const companys = ref([])
function getCompany() {
    proxy.$axios
        .get("user/order/company")
        .then((res) => {
            if (res.data.code == 0) {
                companys.value = res.data.data
                getAddrs()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
const changeCompany = (val) => {
    let index = companys.value.findIndex((item) => item.company_id == val)
    company_name.value = index > -1 ? companys.value[index].title : ""
}
// 站点自提
const dc_id = ref("")
const sites = ref([])
function getSites() {
    proxy.$axios
        .get("user/order/selfList")
        .then((res) => {
            if (res.data.code == 0) {
                sites.value = res.data.data
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 创建订单
 * @param {Boolean} form_loading  按钮状态
 * @param {Number} pay_code  订单状态，[money:余额支付,credit:授信额支付]
 * @param {String} addr_id 收货地址
 * @param {String} pei_type 配送方式，0是自提，1是物流
 * @param {String} order_remarks 订单备注
 * @param {String} pack_amount 打包费
 * @param {String} freight 运费
 * @param {String} delivery_day 订单归属日期
 * @param {String} self_contact 自提联系人
 * @param {String} self_mobile 自提联系电话
 */
const form_loading = ref(false)
const pay_code = ref("money")
const addr_id = ref("")
const order_remarks = ref("")
const pack_amount = ref(0)
const freight = ref(0)
const delivery_day = ref("")
const self_mobile = ref("")
const self_contact = ref("")
const clickOrders = () => {
    let regTel = /^1[23456789]\d{9}$/
    if (select_goods.value.length == 0 || select_goods.value[0].product_id === 0) {
        proxy.$message({ message: "请选择商品", type: "warning" })
        return
    }
    let arrs = []
    for (let i = 0; i < select_goods.value.length; i++) {
        if (select_goods.value[i].product_price == "") {
            proxy.$message({ message: "请输入商品价格", type: "warning" })
            return
        }
        if (select_goods.value[i].product_id > 0) {
            arrs.push({
                pid: select_goods.value[i].product_id,
                price: select_goods.value[i].product_price,
                num: select_goods.value[i].nums,
            })
        }
    }
    if (prices.value == 0) {
        proxy.$message({ message: "请输入花材费", type: "warning" })
        return
    }
    if (pay_code.value === "money" && prices.value - objs.value.money > 0) {
        proxy.$message({ message: "用户余额不足！", type: "warning" })
        return
    }
    if (pay_code.value === "credit" && prices.value - objs.value.credit > 0) {
        proxy.$message({ message: "用户授信额度不足！", type: "warning" })
        return
    }
    if (pack_amount.value == 0) {
        proxy.$message({ message: "请输入打包费", type: "warning" })
        return
    }
    if (freight.value === "") {
        proxy.$message({ message: "请输入运费", type: "warning" })
        return
    }
    // 自提
    if (pei_type.value == 0 && !self_contact.value) {
        proxy.$message({ message: "请输入自提联系人", type: "warning" })
        return
    }
    if (pei_type.value == 0 && !regTel.test(self_mobile.value)) {
        proxy.$message({ message: "联系电话格式错误", type: "warning" })
        return
    }
    if (pei_type.value == 0 && !dc_id.value) {
        proxy.$message({ message: "请选择自提点", type: "warning" })
        return
    }
    // 物流
    if (pei_type.value == 1 && !company_id.value) {
        proxy.$message({ message: "请选择物流公司", type: "warning" })
        return
    }
    if (delivery_day.value === "") {
        proxy.$message({ message: "请选择订单归属日期", type: "warning" })
        return
    }

    postOrder(arrs)
}
function postOrder(arrs) {
    let params = {
        uid,
        product: arrs,
        price: prices.value,
        pay_code: pay_code.value, // [money:余额支付,credit:授信额支付]
        pei_type: pei_type.value, // 配送方式[0:自提,1:快递]
        addr_id: pei_type.value == 0 ? dc_id.value : addr_id.value, // 自提跟物流公用地址ID
        pay_code: pay_code.value,
        amount: prices.value, // 实际金额
        pack_amount: pack_amount.value, // 打包费
        freight: freight.value, // 运费
        delivery_day: delivery_day.value, // 订单归属日期
        intro: order_remarks.value,
    }
    // pei_type 0是自提，1是物流
    if (pei_type.value == 0) {
        params.self_contact = self_contact.value
        params.self_mobile = self_mobile.value
    } else {
        params.company_id = company_id.value // 物流公司ID
    }
    form_loading.value = true
    proxy.$axios
        .post("user/order/handle", params)
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
                proxy.$message({ message: "创建会员订单成功！", type: "success" })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}

// 订单预览
const drawerOrder = ref(false)
const prevArrs = ref([])
const clickPreview = () => {
    drawerOrder.value = true
    prevArrs.value = JSON.parse(JSON.stringify(select_goods.value))
    prevArrs.value.splice(prevArrs.value.length - 1, 1) // 去除最后空数据，方便下面按中文排序

    // 使用sort()、localeCompare()进行中文数组首字母的排序
    // sort()函数会对使用的数组对象进行排序，排序规则安装字符编码顺序排序，
    // localeCompare()方法，比较两个字符串的先后顺序，可用于判断中文，该比较基于本地区域设置的字符顺序
    // 如果当前字符串对象排在b之前，则localeCompare()返回 -1；如果当前字符串排在b之后，则返回 1；如果两个字符串相等，则返回 0
    prevArrs.value.sort((str1, str2) => str1.product_name.localeCompare(str2.product_name))

    // 当数组长度为奇数时补齐剩余表格，使其变成一个完整的table
    if (prevArrs.value.length % 2 > 0) {
        prevArrs.value.push({
            product_name: "",
            norm: "",
        })
    }
}

/**
 * 添加地址
 * @param {Boolean} dialogAddr 弹窗状态
 * @param {Array} ruleRef 表单规则
 * @param {Object} ruleForm  表单字段
 * @param {Object} ruleCheck  表单提示
 */
const dialogAddr = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    name: "",
    tel: "",
    area_code: [],
    address: "",
    lat_lng: [],
})
const ruleCheck = reactive({
    name: [{ required: true, message: "请输入收货人姓名", trigger: "blur" }],
    tel: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    lat_lng: [{ required: true, type: "array", message: "请选择当前位置的经纬度", trigger: "change" }],
    area_code: [{ required: true, type: "array", message: "请选择省市区", trigger: "change" }],
    address: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            let areas = cascaderRef.value.getCheckedNodes()
            form_loading.value = true
            let data = {
                uid: uid,
                contact: ruleForm.name,
                mobile: ruleForm.tel,
                province_code: ruleForm.area_code ? ruleForm.area_code[0] : "",
                city_code: ruleForm.area_code ? ruleForm.area_code[1] : "",
                district_code: ruleForm.area_code ? ruleForm.area_code[2] : "",
                province: areas[0].pathLabels[0],
                city: areas[0].pathLabels[1],
                district: areas[0].pathLabels[2],
                lat: ruleForm.lat_lng[0],
                lng: ruleForm.lat_lng[1],
                addr: areas[0].pathLabels[0] + areas[0].pathLabels[1] + areas[0].pathLabels[2],
                house: ruleForm.address,
            }
            proxy.$axios
                .post("user/addr/add", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogAddr.value = false
                        proxy.$message({ message: "添加成功！", type: "success" })
                        addrArrs.value = []
                        getAddrs()
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeAddr = () => {
    resetForm(ruleRef.value)
    dialogAddr.value = false
}
// 获取地址
const addrArrs = ref([])
function getAddrs() {
    proxy.$axios
        .get("user/addr/index", {
            params: {
                uid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                addrArrs.value = res.data.data
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 选择省市区
 * @param {Array} allArea 存放省市区数组
 * @param {Object} cascaderRef 容器ref
 * @param {Function} getArea 请求json
 */
const allArea = ref([])
const cascaderRef = ref(null)
const props = {
    label: "name",
    value: "adcode",
    children: "districts",
}
function getArea() {
    proxy.$axios
        .get("gaode-area.json")
        .then((res) => {
            let result = res.data.districts
            allArea.value = result[0].districts
        })
        .catch((err) => {})
}

/**
 * 腾讯地图-根据地址获取经纬度
 * @param {Boolean} dialogMap 地图弹窗
 * @param {String} locations 经纬度地址
 * @param {String} addrs 搜索字段
 * @param {Object} map Map 构造函数创建地图
 * @param {Function} initMap 初始化地图
 */
var map = null,
    marker = null,
    eventDragend = null
const addrs = ref("")
const locations = ref("")
const dialogMap = ref(false)
const search_btn = ref(false)
const handleSearch = () => {
    if (addrs.value == "") {
        proxy.$message({ message: "请输入详细地址！", type: "warning" })
        return
    }
    search_btn.value = true
    jsonp("https://apis.map.qq.com/ws/geocoder/v1/?address=", {
        output: "jsonp",
        address: addrs.value,
        key: "RIRBZ-LYM6O-Z73WF-S4A5Z-IEUB5-DXFYZ",
    })
        .then((res) => {
            search_btn.value = false
            if (res.status == 0) {
                locations.value = `${res.result.location.lat},${res.result.location.lng}`
                let center = new qq.maps.LatLng(res.result.location.lat, res.result.location.lng)
                map.panTo(center) // 重新设置地图中心点
                initMap(res.result.location.lat, res.result.location.lng)
            } else {
                proxy.$message({ message: res.message, type: "warning" })
            }
        })
        .catch((err) => {
            search_btn.value = false
        })
}
const clickLatAndLng = () => {
    dialogMap.value = true
    setTimeout(() => {
        initMap()
    }, 50)
}
const confirmMap = () => {
    dialogMap.value = false
    ruleForm.lat_lng = locations.value.split(",")
}
function initMap(lat = 39.90923, lng = 116.397428) {
    let myLatlng = new qq.maps.LatLng(lat, lng)
    let myOptions = {
        zoom: 17,
        center: myLatlng,
    }
    map = new qq.maps.Map(document.getElementById("container"), myOptions)
    marker = new qq.maps.Marker({
        // 设置标记
        position: myLatlng,
        draggable: true,
        animation: qq.maps.MarkerAnimation.DROP,
        map: map,
    })
    eventDragend = qq.maps.event.addListener(marker, "dragend", function (e) {
        // 监听标记拖动
        let latLng = marker.getPosition()
        map.setCenter(latLng)
        let lats = latLng.lat.toFixed(6)
        let lng = latLng.lng.toFixed(6)
        locations.value = `${lats},${lng}`
    })
}
</script>
<script>
export default {
    name: "MemberCreateOrder",
}
</script>

<style lang="less" scoped>
.xq-box {
    height: 1000px;
    .prev-box {
        margin-top: @margin-base;
    }
    .prev-item {
        width: 50%;
    }
    .prev-table {
        font-size: @font-size-md;
        color: #333;
        .table-head {
            display: flex;
            border-top: 1px solid #999;
            border-left: 1px solid #999;
            & > div {
                text-align: center;
                line-height: 30px;
                flex: none;
                height: 30px;
            }
        }
        .table-body {
            display: flex;
            flex-flow: row wrap;
            border-left: 1px solid #999;
        }
        .table-body__left {
            flex: none;
            border-bottom: 1px solid #999;
            & > div {
                text-align: center;
                line-height: 30px;
                flex: none;
                height: 30px;
                border-right: 1px solid #999;
            }
        }
        .table-foot {
            margin-top: @margin-sm;
            .table-foot__line {
                justify-content: flex-end;
                .table-foot__title {
                    margin-left: @margin-xl;
                }
            }
        }
        .table-none {
            text-align: center;
            line-height: 50px;
            border-right: 1px solid #999;
        }
        .table-head__one,
        .table-head__three,
        .table-head__five {
            width: 80px;
        }
        .table-head__two {
            flex: none;
            width: 191px;
        }
        .table-head__four,
        .table-head__six {
            width: 90px;
        }
        .table-head__null {
            width: 41px;
            height: 30px;
        }
    }
}
.good-list {
    height: 380px;
    overflow-y: auto;
    &::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 4px;
        /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }

    &::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        border-radius: 10px;
        background: @gray-4;
    }

    &::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        border-radius: 10px;
        background: #f1f1f1;
    }
    .good-item {
        display: flex;
        align-items: center;
        border-bottom: @border-gray;
        padding: @padding-xs @padding-mdl;
        font-size: @font-size-md;
        color: @gray-8;
        &:hover {
            cursor: pointer;
            background-color: #f5f7fa;
        }
        &:last-child {
            border: 0;
        }
        .good-pid {
            width: 46px;
            margin-right: @margin-sm;
            flex: none;
        }
        .good-img {
            width: 30px;
            height: 30px;
            flex: none;
            border-radius: @radius-xs;
        }

        .good-title {
            max-width: 200px;
            margin: 0px @margin-md;
        }
        .good-attr {
            margin-right: @margin-md;
        }
    }

    .good-none {
        text-align: center;
        line-height: 50px;
    }
    .disabled {
        color: @gray-5;
        &:hover {
            cursor: not-allowed;
        }
    }
}

.good-foot {
    margin-top: 12px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .detail-item {
        width: auto;
    }
    :deep(.detail-item__right) {
        flex: none;
        padding-right: 0;
    }
}
.od-one {
    display: flex;
    margin-top: @margin-sm;
    .od-one__item {
        flex: none;
        width: 33.33%;
        p {
            width: 100%;
            margin-bottom: @margin-sm;
            font-size: @font-size-md;
            color: @gray-8;
            .price-icon {
                font-size: @font-size-sm;
            }
        }
    }
}

#container {
    width: 100%;
    height: 400px;
}
.mco-item {
    margin-bottom: 40px;
}
.table-mb {
    margin: @margin-lg 0px;
    .table-oper {
        .el-icon {
            cursor: pointer;
            &:hover {
                color: @themes;
            }
        }
    }
}
:deep(.el-radio) {
    height: auto;
}
.exp-detail {
    width: auto;
    .el-select {
        width: 400px;
        margin-right: @margin-mdl;
    }
    :deep(.detail-item__left) {
        line-height: 36px;
    }
    :deep(.el-date-editor--date),
    :deep(.el-input__wrapper),
    :deep(.el-input__inner) {
        height: 36px;
        line-height: 36px;
    }
}
</style>

<style lang="less">
.mco-drawer {
    .el-drawer__header {
        padding: 13px 16px !important;
    }

    .el-drawer__body {
        &::-webkit-scrollbar {
            /*滚动条整体样式*/
            width: 4px;
            /*高宽分别对应横竖滚动条的尺寸*/
            height: 1px;
        }

        &::-webkit-scrollbar-thumb {
            /*滚动条里面小方块*/
            border-radius: 10px;
            background: @gray-4;
        }

        &::-webkit-scrollbar-track {
            /*滚动条里面轨道*/
            border-radius: 10px;
            background: #f1f1f1;
        }
    }
}
</style>
